import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/patrol/offline_patrol_list_data.dart';
import 'package:ls_work/sql/AppDbUtils.dart';
import 'package:ls_work/sql/protral/offline_submit_patrol_entity.dart';
import 'package:ls_work/sql/protral/patrol_task_entity.dart';
import 'package:ls_work/sql/protral/patrol_task_point_entity.dart';
import 'package:ls_work/util/ext_utils.dart';

import '../../net/response/patrol/patrol_detail_data.dart';
import '../../net_configs.dart';

class PatrolTaskModel extends BaseMvvmModel {
  @override
  void onCleared() {}

  ///获取本地任务列表
  Future<OfflineTaskInfo> getOfflineTask() async {
    var data = await HttpGo.instance.postData(PatrolApi.offlineTask);
    if ("0" == data['code']) {
      if(data['data']==null){
        return OfflineTaskInfo(taskList: [], taskPointList: []);
      }
      var list = ((data['data']['guardTaskExecuteBeanList'] as List) ?? [])
          .map((e) => OfflinePatrolListData.fromJson(e))
          .toList();
      List<PatrolTaskData> taskList = [];
      List<PatrolTaskPointData> taskPointList = [];
      for (var item in list) {
        var task = PatrolTaskData.fromJson(item.toJson());
        taskList.add(task);
        var list = item.guardTaskPointExecuteBeanList?.map((e) {
          var point = PatrolTaskPointData.fromJson(e.toJson());
          point.patrolRange = task.patrolRange;
          point.startTime = task.startDate;
          point.endTime = task.endDate;
          point.branchId = task.branchId;
          point.require = point.guardRequire;
          point.patrolName = task.name;
          return point;
        }).toList();
        taskPointList.addAll(list??[]);
      }
      return OfflineTaskInfo(taskList: taskList, taskPointList: taskPointList);
    } else {
      throw data['msg'];
    }
  }

  Future<void> insetTask(OfflineTaskInfo task) async {
    await AppDbUtils.instance().patrolTaskDao.addTaskList(task.taskList);
    await AppDbUtils.instance()
        .patrolTaskDao
        .addTaskPointList(task.taskPointList);
  }

  ///删除全部
  Future<void> deleteAll() async {
    await AppDbUtils.instance().patrolTaskDao.deleteAll();
  }

  ///获取本地任务
  Future<List<PatrolTaskData>> getLocalTask() async {
    var format = ['yyyy', '-', 'mm', '-', 'dd'];
    return await AppDbUtils.instance()
        .patrolTaskDao
        .findTodayTask(DateTime.now().toDateStr(format));
  }

  ///获取任务巡防点
  Future<List<PatrolTaskPointData>> getTaskPoint(int taskId) async {
    return await AppDbUtils.instance().patrolTaskDao.findPointByTask(taskId);
  }

  ///二维码扫码
  Future<List<PatrolTaskPointData>> searchTaskPointByQrcode(
      String qrcode) async {
    var list =
        await AppDbUtils.instance().patrolTaskDao.findPointByQrcode(qrcode);
    if (list.isEmpty) {
      return [];
    }
    var pointList = <PatrolTaskPointData>[];
    for (var point in list) {
      if (DateTime.now()
          .isInTimeRange(startTime: point.startTime??"", endTime: point.endTime??"")) {
        pointList.add(point);
      }
    }
    if (pointList.isEmpty) {
      return [];
    }

    if (pointList.length == 1) {
      return pointList;
    }

    pointList.sort((o1, o2) {
      return o1.startTime!.compareTo(o2.startTime!);
    });
    return pointList;
  }

  ///获取本地记录
  Future<List<OfflineSubmitPatrolData>> getLocalRecord() async {
    return await AppDbUtils.instance().patrolTaskDao.getLocalRecord();
  }

  Future<Map<String, dynamic>> uploadLocalRecord(
      OfflineSubmitPatrolData data) async {
    try {
      var map = data.toJson();
      var result = await HttpGo.instance.postData(PatrolApi.uploadLocalRecord,
          data: map,
          options: Options(
            contentType: Headers.formUrlEncodedContentType,
            sendTimeout: Duration(milliseconds: 8000),
            receiveTimeout: Duration(milliseconds: 8000),
          ));
      if ("0" == result["code"]) {
        return {"success": true, "msg": ""};
      } else {
        if(result['msg'].toString().contains("已巡查")){
          return {"success": true, "msg": result['msg']};
        }else{
          return {"success": false, "msg": result['msg']};
        }

      }
    } catch (e) {
      return {"success": false, "msg": "服务器上传出现问题"};
    }
  }


  ///直接提交
  Future<Map> submitPatrolDirect(String code) async {
    var map = {
      "content": code,
    };
    var result = await HttpGo.instance
        .postData(PatrolApi.scanCode, data: map, options: urlencodedHeader);

    if ("0" == result["code"]) {
      var detailList = (result['data'] as List ?? [])
          .map((e) => PatrolDetailData.fromJson(e))
          .toList();
      if(detailList.isNotEmpty){
        var detailData = detailList.first;
        var submitMap = {
          "id": detailData.id,
          "resultStatus": "2",
          "feedback": "",
        };

        var submitResult = await HttpGo.instance.postData(PatrolApi.submitPatrol,
            data: submitMap, options: urlencodedHeader);
        if("0"==submitResult['code']){
          return submitResult;
        }else{
          throw submitResult['msg'];
        }
      }else{
        throw "未获取到任务信息";
      }
    } else {
      throw result['msg'];
    }
  }
}

class OfflineTaskInfo {
  List<PatrolTaskData> taskList;
  List<PatrolTaskPointData> taskPointList;

  OfflineTaskInfo({required this.taskList, required this.taskPointList});
}
